import gcoord from "../../miniprogram_npm/gcoord/dist/gcoord";
import config from "../../utils/enum.js";
Page({
  /**
   * 页面的初始数据
   */
  data: {
    status: '未走访',
    markers: [],
    list: [
      {
        shortName: '苏州征信',
        name: '苏州征信有限公司',
        labelList: ['未走访', '问卷已完成']
      },
    ],
    selectOne: '',
    selectOneIndex: '',
    pageNum: 1,
    showList: true,
    onlyView: false,
    userId: '',
    isLoading: true,
    searchContent: '',
    total: ''
  },


  selectTab (e) {
    console.log(e.detail, 'name')
    this.setData({
      status: e.detail.title
    })
    this.setData({
      pageNum: 1,
      list: [],
      markers: [],
      selectOne: '',
      selectOneIndex: ''
    })
    // 重新初始化点
    this.getList()
  },
  selectOne (e) {
    // console.log(e, 'e')
    if (this.data.onlyView) {
      wx.navigateTo({
        url: `/sub_suzhou/qiyezoufangdetail/qiyezoufangdetail?corpCredit=${e.currentTarget.dataset.key}&agencyName=${e.currentTarget.dataset.name}&latitude=${e.currentTarget.dataset.latitude}&longitude=${e.currentTarget.dataset.longitude}&distance=${e.currentTarget.dataset.distance || ''}&onlyView=${this.data.onlyView}&userId=${this.data.userId}&corpType=${e.currentTarget.dataset.type}&contactPhone=${e.currentTarget.dataset.phone}`,
      });
    } else {
      wx.navigateTo({
        url: `/sub_suzhou/qiyezoufangdetail/qiyezoufangdetail?corpCredit=${e.currentTarget.dataset.key}&agencyName=${e.currentTarget.dataset.name}&latitude=${e.currentTarget.dataset.latitude}&longitude=${e.currentTarget.dataset.longitude}&distance=${e.currentTarget.dataset.distance || ''}&corpType=${e.currentTarget.dataset.type}&contactPhone=${e.currentTarget.dataset.phone}`,
      });
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onShow () {
    // let pages = getCurrentPages();
    // let currentPages = pages[pages.length - 1]
    // console.log(currentPages.options, '可以获得参数')
    // if (currentPages.options.permission && currentPages.options.permission == '1') {
    //   this.setData({
    //     onlyView: true,
    //     userId: currentPages.options.userId
    //   })
    // }
    // 步骤一、常见地图实例对象
    this.mapCtx = wx.createMapContext("myMap");
    this.setData({
      pageNum: 1,
      list: [],
      markers: [],
      selectOne: '',
      selectOneIndex: '',
      isLoading: true
    })
    const that = this;
    // 获取当前的位置信息
    getApp().globalData.getLocation({
      type: "gcj02",
      success (res) {
        // 获取当前的定位
        that.initInfoByCenter(res);
      },
    });
  },
  // 返回到当前定位视窗
  locationBack () {
    this.mapCtx.moveToLocation();
  },
  tabList () {
    this.setData({
      showList: !this.data.showList
    })
    console.log(this.data.showList, 'showList')
  },
  markerCalloutTap (e) {
    console.log(e, 'e')
    const selectOne = this.data.list[e.markerId]
    this.setData({
      selectOne: selectOne,
      selectOneIndex: e.markerId
    })
    this.data.markers.forEach((val, index) => {
      if (index === e.markerId) {
        val.iconPath = 'https://zx-1311146360.cos.ap-shanghai.myqcloud.com/version01/center-location2.png'
      } else {
        val.iconPath = 'https://zx-1311146360.cos.ap-shanghai.myqcloud.com/version01/zhoubian1.png'
      }
    })
    this.setData({
      markers: this.data.markers
    })
  },
  initInfoByCenter (res) {
    //console.log(res)
    this.setData({
      // longitude: this.transMarker([res.longitude, res.latitude])[0],
      // latitude: this.transMarker([res.latitude, res.latitude])[1],
      longitude1: res.longitude,
      latitude1: res.latitude,
    });
    this.getInfos()
  },
  // 加载更多
  scrollBottom () {
    if(this.data.list.length < this.data.total) {
      this.getList()
    }
  },

  async getInfos () {
    // 获取个人信息
    const { data } = await getApp().globalData.request("/login/getCurrentUserInfo", {}, "POST");
    console.log(data, 'data')
    // data.avatarUrl = data.avatarUrl || 'https://zx-1311146360.cos.ap-shanghai.myqcloud.com/personalCenter/2.png'
    wx.setStorageSync("userInfo", data)
    // 获取走访列表
    this.getList()
  },
  onChange(e) {
    this.setData({
      searchContent: e.detail,
    });
  },
  async getList () {
    this.setData({
      isLoading: true
    })
    const userInfo = wx.getStorageSync('userInfo')
    const params = {
      corpName: this.data.searchContent,
      userLng: this.transMarker([this.data.longitude1, this.data.latitude1])[0],
      userLat: this.transMarker([this.data.longitude1, this.data.latitude1])[1],
      userId: this.data.userId ? this.data.userId : userInfo.userId,
      // userId: 'ecb1e7e07f6242899194f838f1f9a767',
      status: this.data.status,
      pageSize: 15,
      pageNum: this.data.pageNum,
    }
    console.log({ ...params }, 'params');
    const res = await getApp().globalData.request(
      // "/visit/getList",
      "/visit/getVisitCorpList",
      { ...params },
      "POST"
    );
    console.log(res, 'res')
    if (res.data.list.length > 0) {
      // 处理颜色和背景
      const keyValues = config.visit_suzhou
      res.data.list.forEach(pre => {
        let keyList = []
        pre.statusList.forEach(poi => {
          const oneObj = keyValues.find(pr => pr.text === poi)
          keyList.push(oneObj)
        })
        pre.keyList = keyList
      })
      this.setData({
        pageNum: ++this.data.pageNum,
        total: res.data.total,
        list: this.data.list.concat(res.data.list)
      })
    }
    this.setData({
      isLoading: false
    })
    // 渲染地图上的坐标点
    this.initMarkers();
  },
  goSearch() {
    this.setData({
      pageNum: 1,
      list: []
    })
    this.getList()
  },
  initMarkers () {
    const markers = [];
    console.log(this.data.list, 'list')
    this.data.list.forEach((val, index) => {
      if (val.longitude) {
        const zuobiao = this.transMarker1([val.longitude, val.latitude]);
        const longitude = zuobiao[0];
        const latitude = zuobiao[1];
        markers.push({
          id: index,
          latitude: latitude,
          longitude: longitude,
          iconPath:
            "https://zx-1311146360.cos.ap-shanghai.myqcloud.com/version01/zhoubian1.png",
          width: 14,
          height: 21,
        });
      }
    });
    this.setData({
      markers: markers,
    });
    // console.log(markers, "markers");
  },

  toprodetail (e) {
    wx.navigateTo({
      url: `/pages/mapDetail/mapDetail?corpKey=${e.detail.corpKey}&latitude=${e.detail.latitude}&longitude=${e.detail.longitude}&distance=${''}`,
    });
  },

  // 坐标系转化
  transMarker (item) {
    const resae = gcoord.transform(
      [item[0], item[1]],
      gcoord.GCJ02, // 当前坐标系
      gcoord.BD09 // 目标坐标系
    );
    return resae;
  },

  // 中心点坐标转化
  transMarker1 (item) {
    const resae = gcoord.transform(
      [item[0], item[1]],
      gcoord.BD09, // 当前坐标系
      gcoord.GCJ02 // 目标坐标系
    );
    return resae;
  },

  punch (e) {
    wx.navigateTo({
      url: `/sub_suzhou/punch/punch?shortName=${e.detail.shortName}&corpName=${e.detail.corpName}&corpCredit=${e.detail.corpCredit}&id=${e.detail.id}`,
    })
  },

  onLoad (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide () { },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload () { },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh () { },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom () {
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage () { },
});
